<?php

namespace KevinSoft\MultiLanguage\Middlewares;

use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Lang;
use KevinSoft\MultiLanguage\MultiLanguage;

class MultiLanguageMiddleware
{
    public function handle($request, Closure $next)
    {
        $languages = MultiLanguage::config('languages');
        $cookie_name = MultiLanguage::config('cookie-name', 'locale');

        if (Cookie::has($cookie_name) && array_key_exists(Cookie::get($cookie_name), $languages)) {
            App::setLocale(Cookie::get($cookie_name));
        } else {
            $default = MultiLanguage::config('default');
            if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
                $languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
                if (preg_match("/zh/i", $languages[0])) {
                    $default = "zh-CN";
                } else {
                    $default = "en";
                }
            }
            App::setLocale($default);
        }
        if (Lang::has('admin.admin_name')) {
            config(['admin.name' => trans('admin.admin_name')]);
        }
        if (Lang::has('admin.admin_title')) {
            config(['admin.title' => trans('admin.admin_title')]);
        }
        if (Lang::has('admin.admin_logo')) {
            config(['admin.logo' => '<b>' . trans('admin.admin_logo') . '</b>']);
        }
        if (Lang::has('admin.admin_logo_mini')) {
            config(['admin.logo-mini' => '<b>' . trans('admin.admin_logo_mini') . '</b>']);
        }
        return $next($request);
    }
}
